<?php
/**
 * @package Autogenerator for Joomla!
 * @version 3.0.0
 * @author Truong Cong Duc <truongcongduc4@gmail.com>
 * @link autogenerator.blogspot.com
 * @copyright (c) 2013, Truong Cong Duc
 * @license GNU General Public License version 2 or later; see LICENSE.txt
 */

defined('_JEXEC') or die;

class AutogeneratorModelXml_attributes extends JModelList
{
	public function __construct($config = array())
	{
		if (empty($config['filter_fields'])) {
			$config['filter_fields'] = array(
				'id', 'axa.id',
				'title', 'axa.title',
				'default', 'axa.default',
				'description', 'axa.description',
				'ordering', 'axa.ordering'
			);
		}
		
		parent::__construct($config);
	}
	
	protected function populateState($ordering = null, $direction = null)
	{
		$app = JFactory::getApplication();
		
		$search = $this->getUserStateFromRequest($this->context . '.filter.search', 'filter_search');
		
		$this->setState('filter.search', $search);
		
		parent::populateState('axa.title', 'asc');
	}
	
	protected function getStoreId($id = '')
	{
		// Compile the store id.
		$id	.= ':'.$this->getState('filter.search');
		
		return parent::getStoreId($id);
	}
	
	public function getItems()
	{
		return parent::getItems();
	}
	
	protected function getListQuery()
	{
		$db	= $this->getDbo();
		$oQuery = $db->getQuery(true);
		
		$oQuery->select($this->getState('list.select', 'axa.id, axa.title, axa.default, axa.description, axa.ordering'));
		$oQuery->from('#__auto_xml_attribute AS axa');
        
		// For search.
		$search = $this->getState('filter.search');
		if (!empty($search)) {
			if (stripos($search, 'id:') === 0) {
				$oQuery->where('axa.id = ' . (int) substr($search, 3));
			} else {
				$search = $db->Quote('%' . $db->escape($search, true) . '%');
				$oQuery->where('(axa.title LIKE ' . $search . ' OR axa.description LIKE ' . $search . ')');
			}
		}
		
		// For ordering.
		$orderCol = $this->state->get('list.ordering', 'axa.title');
		$orderDirn = $this->state->get('list.direction', 'asc');
		$oQuery->order($db->escape($orderCol . ' ' . $orderDirn));
		
		return $oQuery;
	}
}
